<?php

namespace App\Http\Controllers;

use App\Models\CityList;
use Illuminate\Http\Request;

class CityListController extends Controller
{
    public function getLiveCity()
    {
        $location = request()->input('location');

        $city = CityList::where('key', $location)->first();
        if ($city) {
            return response()->json(['recode' => 1, 'res' => ['code' => $city->key, 'name' => $city->name]]);
        }
        $location = substr($location, 0, 4) . '00';
        $city = CityList::where('key', $location)->first();
        if ($city) {
            return response()->json(['recode' => 1, 'res' => ['code' => $city->key, 'name' => $city->name]]);
        }
        $location = substr($location, 0, 2) . '0000';
        $city = CityList::where('key', $location)->first();
        if ($city) {
            return response()->json(['recode' => 1, 'res' => ['code' => $city->key, 'name' => $city->name]]);
        }
        return response()->json(['recode' => 0, 'msg' => '未找到城市']);
    }

    public function getCityInfo()
    {
        $city = request()->input('city');
        $city = CityList::where('key', $city)->first();
        if ($city) {
            return response()->json([
                'recode' => 1,
                'city' => [
                    "code" => $city->key,
                    'name' => $city->name,
                ],
            ]);

        }
        return response()->json([
            'recode' => 0,
            'city' => [
                "code" => 0,
                'name' => '城市不存在',
            ],
        ]);

    }

    public function getArea()
    {
        $city = request()->input('city');
        $cityLike = rtrim($city, '0');
        if (strlen($cityLike) % 2 === 1) {
            $cityLike = $cityLike . '0';
        }
        $cityLike .= '%';

        $list = CityList::where([['key', 'like', $cityLike], ['key', '!=', $city]])->pluck('name');

        return response()->json([
            'recode' => 1,
            'list' => $list,
        ]);
    }

    public function getAreaByChild()
    {
        $city = request()->input('city');
        $name = CityList::where('key', $city)->value('name');

        $city = substr($city, 0, 4);
        $city .= '%';

        $list = CityList::where([['key', 'like', $city]])->pluck('name');

        $i = 0;
        foreach ($list as $vo) {
            if ($vo == $name) {
                break;
            }
            $i++;
        }

        return response()->json([
            'recode' => 1,
            'list' => $list,
            'index' => $i,
        ]);

    }
}
